package com.stone.widget;

import java.sql.SQLException;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.LiveFolders;
import android.text.TextUtils;
import android.util.Log;

public class MyProvider extends ContentProvider {
    private static final String TAG="---------------MyProvider";
	private MyDbHelper myDbHelper;
	/**
	 * UriMatcher类型静态字段用来匹配传入到ContentProvider中的Uri的类
	 * 其构造方法中出入的匹配码是使用match（）方法匹配根路径时返回值，这个匹配码
	 * 可以为一个大于0的数表示匹配，传入-1表示不匹配。NO_MATCH是其自己定义的常量为-1
	 * addUri方法是增加匹配的路径，第一个参数是标识Contentprovider的字符串
	 * 第二个参数是需要匹配的路径，#代表任意数字，*代表任意字符
	 * 第三个参数是必须传入一个大于0的匹配码，用于match()方法对相匹配的URI返回
	 * 相对应的匹配码
	 * 
	 * */
	private static final UriMatcher mUriMatcher;
	static{
		mUriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
		mUriMatcher.addURI(CountryCode.AUTHORITY,"item", CountryCode.ITEM);
		mUriMatcher.addURI(CountryCode.AUTHORITY,"item/#", CountryCode.ITEM_ID);
	    //匹配实时文件夹
		mUriMatcher.addURI(CountryCode.AUTHORITY,"livefolder/",CountryCode.LIVE_FOLDER);
	}
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db=myDbHelper.getWritableDatabase();
		int count=0;
		switch(mUriMatcher.match(uri)){
		//删除这个集合
		case CountryCode.ITEM:
			 count=db.delete(CountryCode.TABLE_NAME, selection,selectionArgs);
		     break;
			 //删除一条记录
		case CountryCode.ITEM_ID:
			String id=uri.getPathSegments().get(1);
			Log.i(TAG, String.valueOf(uri.getPathSegments().size()));
			count=db.delete(CountryCode.TABLE_NAME, CountryCode.FIELD_ID + "=" + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')': "") , selectionArgs);
		    break;
		default:
			 throw new IllegalArgumentException();
		}
		//通知注册在此URI上的观察者数据发生了改变
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
    /**
     * 返回数据的MIME类型的方法，使用UriMacher对uri进行匹配，并返回想对应的
     * MIME类型字符串，若无法匹配传入的URI，抛出IlleagalArgumentException
     * */
	@Override
	public String getType(Uri uri) {
		switch(mUriMatcher.match(uri)){
		case CountryCode.ITEM:
			return CountryCode.CONTENT_TYPE;
		case CountryCode.ITEM_ID:
			return CountryCode.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException();
		}
		
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
	     SQLiteDatabase db=myDbHelper.getWritableDatabase();
	     long rowId=0;
	     //添加数据只能是基于表级别
	     if(mUriMatcher.match(uri)!=CountryCode.ITEM){
	    	 throw new IllegalArgumentException();
	     }
	     rowId=db.insert(CountryCode.TABLE_NAME, CountryCode.FIELD_ID, values);
		 if(rowId>0){
			 Uri noteUri=ContentUris.withAppendedId(CountryCode.CONTENT_URI, rowId);
			 getContext().getContentResolver().notifyChange(uri, null);
		     return noteUri;
		 }
	      return null;
	}
	/**
	 * 每当ContentProvider启动时候都会回调oncreate方法。此方法主要
	 * 执行一些初始化工作，true表示初始化成功，false表示失败。
	 * */
     //创建数据库
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		myDbHelper=new MyDbHelper(getContext(),CountryCode.DATABASE_NAME, null, CountryCode.DATABASE_VERSION);
		Log.i(TAG, "onCreate");
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db=myDbHelper.getReadableDatabase();
		Cursor cursor=null;
		switch(mUriMatcher.match(uri)){
		case CountryCode.ITEM:
			cursor=db.query(CountryCode.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
		    break;
		case CountryCode.ITEM_ID:
			String id=uri.getPathSegments().get(1);
			cursor=db.query(CountryCode.TABLE_NAME, projection, CountryCode.FIELD_ID+"="+id+(!TextUtils.isEmpty(selection) ? " AND (" +selection + ')':""), selectionArgs, null, null, sortOrder);
		//实时文件夹使用,注意此处的as用法
		case CountryCode.LIVE_FOLDER:
			String[] myProjection={CountryCode.FIELD_ID+" AS "+LiveFolders._ID,
			                       CountryCode.FIELD_NAME+" AS "+LiveFolders.NAME,
		                           CountryCode.FIELD_CODE+" AS "+LiveFolders.DESCRIPTION
			};
			cursor=db.query(CountryCode.TABLE_NAME, myProjection, selection, selectionArgs, null, null, sortOrder);
		default:
			throw new IllegalArgumentException();
		}
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db=myDbHelper.getWritableDatabase();
		int count=0;
		switch(mUriMatcher.match(uri)){
		case CountryCode.ITEM:
			count=db.update(CountryCode.TABLE_NAME, values, selection, selectionArgs);
			break;
		case CountryCode.ITEM_ID:
			String id=uri.getPathSegments().get(1);
			count=db.update(CountryCode.TABLE_NAME, values,CountryCode.FIELD_ID+ "=" + id +(!TextUtils.isEmpty(selection) ? " AND ( " +selection + ')' :""), selectionArgs);
			break;
		default :
			throw new IllegalArgumentException();
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

}